package com.xin.springcloudconsumer.controller;

import com.google.gson.Gson;
import com.xin.springcloudconsumer.constant.ChatConstant;
import com.xin.springcloudconsumer.dto.UserDTO;
import com.xin.springcloudconsumer.enums.ConsumerEnum;
import com.xin.springcloudconsumer.feign.UserFeign;
import com.xin.springcloudconsumer.utils.JsonUtil;
import com.xin.springcloudconsumer.utils.Md5Utils;
import com.xin.springcloudconsumer.utils.SessionUtils;
import com.xin.springcloudconsumer.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/chat")
@Slf4j
public class ChatController {
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private Gson gson;
    @Autowired
    private SessionUtils sessionUtils;
    /**
     * 进入聊天
     * @param fid
     * @param map
     * @return
     */
    @GetMapping("/join")
    public ModelAndView chat(@RequestParam(name = "fid",defaultValue = "")String fid,
                             HttpServletRequest request,
                             Map<String,Object> map){

        String uid= sessionUtils.getToken(request);
        String headImage= sessionUtils.getHeadImage(request);
        ResultVO<UserDTO> resultVO = userFeign.findOne(fid);
        if (resultVO.getCode()==1){
            map.put("returnUrl","/friend/findList?uid="+uid);
            map.put("message", ConsumerEnum.USER_NOT_EXIST.getMessage());
            return new ModelAndView("common/msg_error",map);
        }
        String json = JsonUtil.toJson(resultVO.getData());
        UserDTO userDTO = gson.fromJson(json, UserDTO.class);
        //MD5(appid+userName+timestamp(yyyyMMddHHmmss)+apptoken);
        SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
        Date date=new Date();
        String datestr=format.format(date);
        String mdbstr= ChatConstant.APPID+uid+datestr+ChatConstant.APPTOKEN;
        String sig = Md5Utils.MD5Encode(mdbstr, "utf-8", true);
        map.put("fname",userDTO.getNickname());
        map.put("uid",uid);
        map.put("sig",sig);
        map.put("fid",fid);
        map.put("timestamp",datestr);
        map.put("appid",ChatConstant.APPID);
        map.put("headImage",headImage);
        map.put("fheadImage",userDTO.getHeadImage());
        return new ModelAndView("chat/news",map);
    }

}
